import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo, clearCache } from '@/utils/cache/cookies'
import { userApi } from '@/api/user/user'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(getUserInfo())
  const isLoggedIn = ref(!!token.value && !!userInfo.value)

  // 登录
  const login = async (loginForm) => {
    try {
      // 根据角色调用不同的登录API
      const response = await userApi.login(loginForm, loginForm.role)

      if (response.code === 200) {
        // 后端返回的数据结构：{ token, id, username, userType, name, studentId, classId, className }
        const { token: userToken, id, username, userType, name, studentId, classId, className } = response.data

        // 构造统一的用户信息格式
        const userData = {
          id: id,
          username: username,
          name: name,
          role: parseInt(userType === 'student' ? '0' : userType === 'admin' ? '1' : userType === 'super_admin' ? '2' : '0'), // 统一为数字格式
          userType: userType, // 保留原始类型
          // 学生专用字段
          studentId: studentId, // 学号
          classId: classId,     // 班级ID
          className: className  // 班级名称（年级+班级名称格式）
        }

        token.value = userToken
        userInfo.value = userData
        isLoggedIn.value = true

        // 持久化存储
        setToken(userToken)
        setUserInfo(userData)

        ElMessage.success('登录成功')
        return response
      } else {
        ElMessage.error(response.message || '登录失败')
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      ElMessage.error(error.message || '登录失败')
      throw error
    }
  }

  // 登出
  const logout = () => {
    token.value = null
    userInfo.value = null
    isLoggedIn.value = false
    
    // 清除缓存
    clearCache()
    
    ElMessage.success('已退出登录')
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      if (!token.value) {
        throw new Error('未登录')
      }
      
      const response = await userApi.getUserInfo()
      
      if (response.code === 200) {
        userInfo.value = response.data
        setUserInfo(response.data)
        return response.data
      } else {
        throw new Error(response.message || '获取用户信息失败')
      }
    } catch (error) {
      // 如果获取用户信息失败，可能是 token 过期，执行登出
      logout()
      throw error
    }
  }

  // 更新用户信息
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    setUserInfo(userInfo.value)
  }

  // 检查是否有权限
  const hasPermission = (permission) => {
    if (!userInfo.value) return false

    // 根据用户角色判断权限，优先使用数字格式的role
    const userRole = userInfo.value.role
    const userType = userInfo.value.userType

    // 超级管理员拥有所有权限
    if (userRole === 2 || userType === 'super_admin') {
      return true
    }

    // 管理员权限
    if (userRole === 1 || userType === 'admin') {
      return ['admin', 'user'].includes(permission)
    }

    // 学生权限
    if (userRole === 0 || userType === 'student') {
      return permission === 'user'
    }

    return false
  }

  // 检查是否为管理员
  const isAdmin = () => {
    return hasPermission('admin')
  }

  // 初始化用户状态
  const initUserState = () => {
    const cachedToken = getToken()
    const cachedUserInfo = getUserInfo()

    if (cachedToken && cachedUserInfo) {
      token.value = cachedToken
      userInfo.value = cachedUserInfo
      isLoggedIn.value = true
    } else {
      // 如果缓存不完整，清除所有缓存
      token.value = null
      userInfo.value = null
      isLoggedIn.value = false
      clearCache()
    }
  }

  // 初始化
  initUserState()

  return {
    // 状态
    token,
    userInfo,
    isLoggedIn,
    
    // 方法
    login,
    logout,
    fetchUserInfo,
    updateUserInfo,
    hasPermission,
    isAdmin,
    initUserState
  }
})
